﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EntityFrameworks.Entity.Core;
using EntityFrameworks.Entity.Core.CommonEnums;

namespace Common.Background.Controllers
{
    using EntityFrameworks.Data.Core;
    /// <summary>
    /// 角色管理
    /// </summary>
    [Common.Background.Filter.AuthorizationFilter]
    public partial class RoleController : BaseController
    {
        public RoleController()
            : base(new backgroundEntities())
        {
        }
        //
        // GET: /Role/

        public ActionResult Index(string deptName, int? page)
        {
            var model = RoleRepository.GetModel();
            if (!string.IsNullOrWhiteSpace(deptName))
                model = model.Where(i => i.RoleName.Contains(deptName));
            var linq = model.Include(i => i.WebDepartments)
                            .Where(i => i.Status != (int)Status.Deleted)
                            .OrderBy(i => i.SortNumber)
                            .ToPagedList(page ?? 1, PageSize);

            linq.AddParameters = new System.Collections.Specialized.NameValueCollection();
            linq.AddParameters.Add("deptName", deptName);

            if (Request.IsAjaxRequest())
                return PartialView("ListPartial", linq);
            return View(linq);
        }

        //
        // GET: /Role/Details/5

        public ActionResult Details(int id)
        {
            var model = RoleRepository.GetModel()
                                      .Include(i => i.WebManageMenus)
                                      .Include(i => i.WebManageUsers)
                                      .Include(i => i.WebDepartments)
                                      .FirstOrDefault(i => i.ManageRoleID == id);
            return View(model);
        }

        //
        // GET: /Role/Create

        public ActionResult Create()
        {
            FillMenuToViewData();
            return View();
        }

        //
        // POST: /Role/Create

        [HttpPost]
        public ActionResult Create(WebManageRoles entity)
        {
            entity.Status = Status.Normal.GetHashCode();
            entity.UpdateDate = DateTime.Now;
            entity.Operator = string.Empty;
            if (Request.Form.GetValues("OperatorAuthority") == null)
            {
                entity.OperatorAuthority = 0;
            }
            else
            {
                Array.ForEach(Request.Form.GetValues("OperatorAuthority"), i =>
                {
                    entity.OperatorAuthority |= int.Parse(i);
                });
            }
            entity.WebManageMenus =
                base.GetEntitiesByIdArr<WebManageMenus>(MenuRepository, Request.Form["WebManageMenus.MenuID"]);
            if (entity.DepartmentID == 0)
                ModelState.AddModelError("DepartmentID", "請選擇部門");

            if (ModelState.IsValid)
            {
                try
                {
                    RoleRepository.Insert(entity);
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "发生未知错误" + ex.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", "请认识填写表单");
            }

            FillMenuToViewData();//绑定一些东西
            return View();
        }

        //
        // GET: /Role/Edit/5

        public ActionResult Edit(int id)
        {
            FillMenuToViewData();
            var linq = RoleRepository.GetModel()
                                     .Include(i => i.WebManageMenus)
                                     .Include(i => i.WebManageUsers)
                                     .Include(i => i.WebDepartments)
                                     .FirstOrDefault(i => i.ManageRoleID == id);
            return View(linq);
        }
        /// <summary>
        /// 填充菜单数据到viewdata
        /// </summary>
        void FillMenuToViewData()
        {
            ViewBag.MenuList = MenuRepository.GetModel().ToList();
        }


        //
        // POST: /Role/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection form)
        {
            var entity = RoleRepository.Find(id);
            TryUpdateModel(entity);
            entity.Operator = string.Empty;
            entity.RoleName = entity.RoleName ?? string.Empty;
            entity.About = entity.About ?? string.Empty;
            if (Request.Form.GetValues("OperatorAuthority") == null)
            {
                entity.OperatorAuthority = 0;
            }
            else
            {
                Array.ForEach(Request.Form.GetValues("OperatorAuthority"), i =>
                {
                    entity.OperatorAuthority |= int.Parse(i);
                });
            }
            entity.WebManageMenus = base.GetEntitiesByIdArr<WebManageMenus>(
                MenuRepository,
                form["WebManageMenus.MenuID"]);
            //表单元素必须是这种名字格式，否则更新失败
            try
            {
                RoleRepository.Update(entity);
                return RedirectToAction("Index");
            }
            catch
            {
                throw;
            }
        }
        public ActionResult Delete(int id)
        {
            try
            {

                RoleRepository.Update<WebManageRoles>(i => new WebManageRoles
                {
                    ManageRoleID = id,
                    Status = Status.Deleted.GetHashCode()
                });
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
